package cn.edu.csmzxy.rk233x.auth_system.controller;

import cn.edu.csmzxy.rk233x.auth_system.dto.PermissionDTO;
import cn.edu.csmzxy.rk233x.auth_system.dto.ResultDTO;
import cn.edu.csmzxy.rk233x.auth_system.entity.SysPermission;
import cn.edu.csmzxy.rk233x.auth_system.service.SysPermissionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.util.List;

/**
 * @author wumxing
 * @date 2025/10/15 9:54
 * @description 权限管理接口
 */

@Tag(name = "权限管理接口", description = "权限CRUD及树形结构查询")
@RestController
@RequestMapping("/api/sys/permission")
@SecurityRequirement(name = "JWT")
public class SysPermissionController {

    @Resource
    private SysPermissionService sysPermissionService;

    @Operation(summary = "查询权限树形结构", description = "需要permission:list权限")
    @PreAuthorize("hasAuthority('permission:list')")
    @GetMapping("/tree")
    public ResultDTO<List<SysPermission>> getPermissionTree() {
        return ResultDTO.success(sysPermissionService.selectPermissionTree());
    }

    @Operation(summary = "根据角色ID查询权限", description = "需要permission:query权限")
    @PreAuthorize("hasAuthority('permission:query')")
    @GetMapping("/role/{roleId}")
    public ResultDTO<List<Long>> getPermissionByRoleId(
            @Parameter(description = "角色ID") @PathVariable Long roleId) {
        return ResultDTO.success(sysPermissionService.selectPermissionIdsByRoleId(roleId));
    }

    @Operation(summary = "新增权限", description = "需要permission:add权限")
    @PreAuthorize("hasAuthority('permission:add')")
    @PostMapping
    public ResultDTO<?> addPermission(@Valid @RequestBody PermissionDTO permissionDTO) {
        sysPermissionService.addPermission(permissionDTO);
        return ResultDTO.success("权限新增成功");
    }

    @Operation(summary = "编辑权限", description = "需要permission:edit权限")
    @PreAuthorize("hasAuthority('permission:edit')")
    @PutMapping("/{id}")
    public ResultDTO<?> updatePermission(
            @Parameter(description = "权限ID") @PathVariable Long id,
            @Valid @RequestBody PermissionDTO permissionDTO) {
        sysPermissionService.updatePermission(id, permissionDTO);
        return ResultDTO.success("权限修改成功");
    }

    @Operation(summary = "删除权限", description = "需要permission:delete权限")
    @PreAuthorize("hasAuthority('permission:delete')")
    @DeleteMapping("/{id}")
    public ResultDTO<?> deletePermission(@Parameter(description = "权限ID") @PathVariable Long id) {
        sysPermissionService.deletePermission(id);
        return ResultDTO.success("权限删除成功");
    }
}
